package com.iespring.service.app.collect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iespring.bean.app.collect.bo.AddOrDeleteBo;
import com.iespring.bean.app.collect.po.MallCollect;
import com.iespring.bean.app.collect.vo.CollectListVo;
import com.iespring.bean.common.BasePageInfo;
import com.iespring.bean.common.CommonData;
import com.iespring.mapper.app.WxCollectMapper;
import com.iespring.util.UserInfoUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author KeFei
 * @description: 小程序收藏模块
 * @date 2023/1/1 23:58
 */
@Service
public class WxCollectServiceImpl implements WxCollectService {

    @Resource
    WxCollectMapper collectMapper;

    /**
     * 显示收藏商品列表
     *
     * @param basePageInfo
     * @return
     */
    @Override
    public CommonData getCollectList(BasePageInfo basePageInfo) {

        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        // 查询收藏商品
        List<CollectListVo> collectList = collectMapper.getCollectList(basePageInfo.getType());

        PageInfo<CollectListVo> pageInfo = new PageInfo<>(collectList);
        CommonData data = CommonData.data(pageInfo);

        return data;
    }

    /**
     * 收藏或取消收藏商品
     *
     * @param addOrDeleteBo
     */
    @Override
    public void addOrDelete(AddOrDeleteBo addOrDeleteBo) {

        // 判断商品收藏状态
        // deleted=1 --> 结果为true,即商品未收藏 --> 添加收藏
        //      情况一:商品已存在collect表中,但被逻辑删除
        //      情况二:商品未存在collect表中
        // deleted=0 --> 结果为false,即商品已收藏 --> 取消收藏
        if (collectMapper.isCollected(addOrDeleteBo) == null) {
            // 商品未存在collect表中 --> 添加收藏
            // 获取userId
            Integer userId = UserInfoUtils.getUser().getId();
            collectMapper.addNewCollect(new MallCollect(null, userId, addOrDeleteBo.getValueId(), addOrDeleteBo.getType(), new Date(), new Date(), false));
        } else {
            // 商品已存在collect表中
            // 判断商品是否被逻辑删除
            if (collectMapper.isDeleted(addOrDeleteBo)) {
                // 是 --> 添加收藏
                collectMapper.addCollect(addOrDeleteBo);
            } else {
                // 不是 --> 取消收藏
                collectMapper.deleteCollect(addOrDeleteBo);
            }
        }
    }
}
